# coding:utf-8

"""
CopyRight(c)  2017-09-15  Fraplus Corp

Author: Weilin Shen, Xiaodong.yang
Email:  xiaodong.yang@unidt.com
Functions:

we chat server

dependence package:

fralog
handler

"""
import time
import subprocess

from fralog.FraLog import Fralog
from handler.signalhandler import SigProccess

log = Fralog().getFileLog()

#
# 保存数据库即时备份文件的目录
save_dir = "/home/fra/backup"
#
# 保存数据库备份压缩文件的目录
dest_dir = "/home/fra/backup-tar"


class Back(object):
    """
    数据库的备份与恢复
    """

    def __init__(self):
        super(Back).__init__()

    def _gettime(self):
        tm = time.strftime("%Y-%m-%d-%H-%M-%S", time.localtime(time.time()))
        print(tm)
        return tm

    def back(self):
        """
        数据库备份
        :return: 
        """
        global dest_dir, save_dir

        log.info('Back up Mongodb.......')

        cmd = "mongodump --port 27017 -d survey_database -o %s" % (save_dir)
        ret = subprocess.call(cmd, shell=True)
        log.info('Back up ok')
        #
        # 获取当前时间戳，将部分文件压缩保存
        fname = "%s/survey_database-%s.tar.gz" % (dest_dir, self._gettime())
        cmd = "tar -zcvf %s %s/survey_database" % (fname, save_dir)
        log.info(cmd)
        subprocess.call(cmd, shell=True)


if __name__ == '__main__':

    inc = 3600 * 5  # 备份的时间间隔
    log.info('Back Up database in every %d seconds' % (inc))
    bk = Back()
    bk.back()
    sp = SigProccess()
    times = 0
    while True:
        if sp.is_stop():
            log.info('正常退出')
            break
        time.sleep(1)
        times += 1
        if times >= inc:
            times = 0
            bk.back()
